// pages/user/myCart/myCart.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isEdit: false,
		page: 1,
		hasMore: true,
		data: [],
		order_total_price: "0.00",
		isAllChecked: false
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.onPullDownRefresh();
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		this.loadData(1).finally(() => {
			wx.stopPullDownRefresh();
		});
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {
		// if (!this.data.hasMore) return;
		//
		// const page = this.data.page + 1;
		// this.loadData(page);
	},

	// 加载数据列表
	loadData: function(page) {
		return wx.http.post('api/cart/lists', {}).then((res) => {
			// res = res.data.data.list;
			// const hasMore = res.data.length >= res.per_page;
			// const data = page > 1 ? this.data.data.concat(res.data) : res.data;
			// this.setData({
			// 	page: page,
			// 	hasMore: hasMore,
			// 	data: data,
			// });

			const data = [res.data.data];
			data.forEach(it => {
				it.goods_list.forEach(it => {
					it.is_checked = false;
				})
			});

			this.setData({
				data: data,
                isAllChecked: false
			});

            setTimeout(() => this.updateTotalAmount(), 0);
			return res.data;
		}, (err) => {
			console.warn("api/cart/lists", err)
		});
	},

	// 全选/取消全选
	toggleAllChecked: function(e) {
		const value = e.detail.value.length > 0;
		const data = this.data.data;
		const result = {};
		data.forEach((it, idx1) => {
			it.goods_list.forEach((it, idx2) => {
				const key = `data[${idx1}].goods_list[${idx2}].is_checked`;
				result[key] = value;
			});
		});
		this.setData(result);
		setTimeout(() => this.updateTotalAmount(), 0);
	},

	// 选择商品
	toggleGoodsChecked: function(e) {
		const values = e.detail.value.map(it => parseInt(it));
		const data = this.data.data;
		let isAllChecked = true;
		data.forEach((it, idx1) => {
			it.goods_list.forEach((it, idx2) => {
				const isChecked = values.indexOf(idx2) !== -1;
				it.is_checked = isChecked;
				if (!isChecked) isAllChecked = false;
			});
		});
		// console.log(isAllChecked)
		this.setData({
			isAllChecked: isAllChecked
		});
		setTimeout(() => this.updateTotalAmount(), 0);
	},

	// 获取cart_id
	getCartIdList() {
		const data = this.data.data;
		const result = [];
		data.forEach((it) => {
			it.goods_list.forEach((it) => {
				if (!it.is_checked) return;

				result.push(`${it.goods_id}_${it.goods_sku.goods_sku_id}`)
			});
		});
		return result;
	},

	// 删除购物车中的商品
	deleteGoodsTap: function(e) {
		const result = this.getCartIdList();
		return wx.http.get('api/cart/delete', {
			goods_sku_id: result.join(','),
		}).then((res) => {
			this.onPullDownRefresh();
		});
	},

	// 增加/减少商品数量
	modifyGoodsNumTap: function(e) {
		const dataset = e.currentTarget.dataset,
			idx1 = dataset.idx1,
			idx2 = dataset.idx2,
			type = dataset.type,
			isSub = type === '0';

		const item = this.data.data[idx1].goods_list[idx2];
		const url = isSub ? 'api/cart/sub' : 'api/cart/add';
		item.total_num = parseInt(item.total_num);
		const totalNum = isSub ? item.total_num - 1 : item.total_num + 1;
		if (totalNum < 1) {
			return;
		}

		return wx.http.post(url, {
			goods_id: item.goods_id,
			goods_sku_id: item.goods_sku.goods_sku_id,
			goods_num: 1,
		}).then((res) => {
			this.groupSetData(() => {
				const totalNumKey = `data[${idx1}].goods_list[${idx2}].total_num`;
				const totalPriceKey = `data[${idx1}].goods_list[${idx2}].total_price`;
				const totalPrice = new wx.BigNumber(item.goods_price).multipliedBy(totalNum).toFixed(2, wx.BigNumber.ROUND_DOWN);
				this.setData({
					[totalNumKey]: totalNum,
					[totalPriceKey]: totalPrice,
				});
				this.updateTotalAmount();
			});

		});
	},

	// 更新金额显示
	updateTotalAmount() {
		const data = this.data.data;
		let goodsTotalPrice = new wx.BigNumber('0.00');
		data.forEach((it) => {
			it.goods_list.forEach((it) => {
				if (!it.is_checked) return;
				goodsTotalPrice = goodsTotalPrice.plus(it.total_price)
			});
		});
		this.setData({
			order_total_price: goodsTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
		});
	},

	// 编辑
	editTap: function() {
		this.setData({
			isEdit: !this.data.isEdit,
		})
	},

	// 立即购买
	buyTap: function() {
		const result = this.getCartIdList();
		if (!result.length) return;

		console.log('/pages/mall/place-order/place-order?cart_ids=' + result.join(","))

		wx.navigateTo({
			url: '/pages/mall/place-order/place-order?cart_ids=' + result.join(",")
		});
	}
});
